import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type { SysMenu } from '#/api/platform/sysmenu';

import { useAccess } from '@vben/access';

import { z } from '#/adapter/form';
import { COMMON_DICT, MENU_DICT } from '#/api';
import { listMenu } from '#/api/platform/sysmenu';
import { $t } from '#/locales';

const { hasAccessByCodes } = useAccess();

/**
 *
 * @returns 树结构菜单
 */
async function menuSelect() {
  const flatList = await listMenu(); // 获取扁平数组
  const tree = buildTree(flatList); // 构建树形结构

  return tree;
}

function buildTree(flatList: SysMenu[]): SysMenu[] {
  const map = new Map<number | string, SysMenu>(); // 用于快速查找节点
  const tree: SysMenu[] = []; // 存储最终的树形结构

  // 首先将所有节点存入 map 中，便于快速查找
  flatList.forEach((item) => {
    map.set(item.menuId, { ...item, children: [] }); // 确保每个节点都有 children 属性
  });

  // 遍历节点，构建树形结构
  flatList.forEach((item) => {
    const current = map.get(item.menuId); // 获取当前节点
    if (!current) return; // 如果当前节点不存在，跳过

    if (item.parentId) {
      // 如果有父节点
      const parent = map.get(item.parentId);
      if (parent) {
        parent.children.push(current); // 将当前节点添加到父节点的 children 中
      }
    } else {
      tree.push(current); // 如果没有父节点，则为根节点
    }
  });

  return tree;
}

/**
 * 查询参数
 */
export function querySchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'menuName',
      label: $t('menu.name'),
    },
    {
      component: 'ApiTreeSelect',
      componentProps: {
        checkStrictly: true,
        allowClear: true,
        api: menuSelect,
        class: 'w-full',
        labelField: 'menuName',
        valueField: 'menuId',
        childrenField: 'children',
      },
      fieldName: 'parentId',
      label: $t('common.parentNode'),
    },
    {
      component: 'ApiSelect',
      componentProps: {
        buttonStyle: 'solid',
        clearable: true,
        options: [
          { label: $t('common.enabled'), value: COMMON_DICT.STATUS_ENABLE },
          { label: $t('common.disabled'), value: COMMON_DICT.STATUS_DISABLE },
        ],
        optionType: 'button',
      },
      defaultValue: null,
      fieldName: 'status',
      label: $t('common.status'),
    },
  ];
}

/**
 * 获取编辑表单的字段配置。如果没有使用多语言，可以直接export一个数组常量
 */
export function formSchema(): VbenFormSchema[] {
  return [
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          {
            label: $t('menu.type.dictionary'),
            value: MENU_DICT.TYPE_DICTIONARY,
          },
          {
            label: $t('menu.type.menu'),
            value: MENU_DICT.TYPE_MENU,
          },
          {
            label: $t('menu.type.button'),
            value: MENU_DICT.TYPE_BUTTON,
          },
          {
            label: $t('menu.type.innerLink'),
            value: MENU_DICT.TYPE_INNERLINK,
          },
          {
            label: $t('menu.type.outLink'),
            value: MENU_DICT.TYPE_OUTLINK,
          },
        ],
        optionType: 'button',
      },
      defaultValue: MENU_DICT.TYPE_DICTIONARY,
      fieldName: 'menuType',
      label: $t('menu.menuType'),
      formItemClass: 'col-span-2 md:col-span-2',
    },
    {
      component: 'ApiTreeSelect',
      componentProps: {
        checkStrictly: true,
        allowClear: true,
        api: async () => {
          const list = await menuSelect();
          return [
            {
              menuId: 0,
              menuName: '父节点',
              children: list,
            },
          ];
        },
        class: 'w-full',
        labelField: 'menuName',
        valueField: 'menuId',
        childrenField: 'children',
      },
      fieldName: 'parentId',
      label: $t('common.parentNode'),
    },
    {
      component: 'Input',
      fieldName: 'menuName',
      label: $t('menu.name'),
      rules: z
        .string()
        .min(2, $t('ui.formRules.minLength', [$t('menu.name'), 2]))
        .max(20, $t('ui.formRules.maxLength', [$t('menu.name'), 20])),
    },
    {
      component: 'IconPicker',
      componentProps: {
        prefix: 'carbon',
      },
      dependencies: {
        show: (row) => {
          return [
            MENU_DICT.TYPE_DICTIONARY,
            MENU_DICT.TYPE_INNERLINK,
            MENU_DICT.TYPE_MENU,
            MENU_DICT.TYPE_OUTLINK,
          ].includes(row.menuType);
        },
        triggerFields: ['menuType'],
      },
      fieldName: 'icon',
      label: $t('menu.icon'),
    },
    {
      component: 'InputNumber',
      fieldName: 'menuSort',
      label: $t('common.sort'),
      rules: z
        .number()
        .gte(0, $t('ui.formRules.minLength', [$t('common.sort'), 0]))
        .lte(100, $t('ui.formRules.maxLength', [$t('common.sort'), 100])),
    },
    {
      component: 'Input',
      fieldName: 'path',
      label: $t('menu.path'),
      dependencies: {
        show: (row) => {
          return [
            MENU_DICT.TYPE_DICTIONARY,
            MENU_DICT.TYPE_INNERLINK,
            MENU_DICT.TYPE_MENU,
            MENU_DICT.TYPE_OUTLINK,
          ].includes(row.menuType);
        },
        triggerFields: ['menuType'],
      },
    },
    {
      component: 'Input',
      fieldName: 'component',
      label: $t('menu.component'),
      dependencies: {
        show: (row) => {
          return [
            MENU_DICT.TYPE_INNERLINK,
            MENU_DICT.TYPE_MENU,
            MENU_DICT.TYPE_OUTLINK,
          ].includes(row.menuType);
        },
        triggerFields: ['menuType'],
      },
    },
    {
      component: 'Input',
      fieldName: 'query',
      label: $t('menu.query'),
      dependencies: {
        show: (row) => {
          return [
            MENU_DICT.TYPE_INNERLINK,
            MENU_DICT.TYPE_MENU,
            MENU_DICT.TYPE_OUTLINK,
          ].includes(row.menuType);
        },
        triggerFields: ['menuType'],
      },
    },
    {
      component: 'Input',
      fieldName: 'perms',
      label: $t('menu.perms'),
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        options: [
          { label: $t('common.yes'), value: true },
          { label: $t('common.no'), value: false },
        ],
        optionType: 'button',
      },
      defaultValue: true,
      fieldName: 'isVisible',
      label: $t('menu.isVisible'),
      dependencies: {
        show: (row) => {
          return [
            MENU_DICT.TYPE_DICTIONARY,
            MENU_DICT.TYPE_INNERLINK,
            MENU_DICT.TYPE_MENU,
            MENU_DICT.TYPE_OUTLINK,
          ].includes(row.menuType);
        },
        triggerFields: ['menuType'],
      },
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        options: [
          { label: $t('common.enabled'), value: COMMON_DICT.STATUS_ENABLE },
          { label: $t('common.disabled'), value: COMMON_DICT.STATUS_DISABLE },
        ],
        optionType: 'button',
      },
      defaultValue: COMMON_DICT.STATUS_ENABLE,
      fieldName: 'status',
      label: $t('common.status'),
      dependencies: {
        show: (row) => {
          return [
            MENU_DICT.TYPE_DICTIONARY,
            MENU_DICT.TYPE_INNERLINK,
            MENU_DICT.TYPE_MENU,
            MENU_DICT.TYPE_OUTLINK,
          ].includes(row.menuType);
        },
        triggerFields: ['menuType'],
      },
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        options: [
          { label: $t('common.yes'), value: true },
          { label: $t('common.no'), value: false },
        ],
        optionType: 'button',
      },
      defaultValue: false,
      fieldName: 'isCache',
      label: $t('menu.isCache'),
      dependencies: {
        show: (row) => {
          return [MENU_DICT.TYPE_MENU].includes(row.menuType);
        },
        triggerFields: ['menuType'],
      },
    },
  ];
}

/**
 * 获取表格列配置
 * @description 使用函数的形式返回列数据而不是直接export一个Array常量，是为了响应语言切换时重新翻译表头
 * @param onActionClick 表格操作按钮点击事件
 */
export function columnsSchema(
  onActionClick?: OnActionClickFn<SysMenu>,
): VxeTableGridOptions<SysMenu>['columns'] {
  return [
    { title: '序号', type: 'seq', width: 50 },
    {
      field: 'menuName',
      title: $t('menu.name'),
      treeNode: true,
    },
    {
      field: 'menuSort',
      title: $t('common.sort'),
      width: 50,
    },
    {
      field: 'menuType',
      title: $t('menu.menuType'),
      width: 150,
      cellRender: {
        name: 'CellTag',
        options: [
          {
            type: 'info',
            label: $t('menu.type.dictionary'),
            value: MENU_DICT.TYPE_DICTIONARY,
          },
          {
            type: 'primary',
            label: $t('menu.type.menu'),
            value: MENU_DICT.TYPE_MENU,
          },
          {
            type: 'danger',
            label: $t('menu.type.button'),
            value: MENU_DICT.TYPE_BUTTON,
          },
          {
            label: $t('menu.type.innerLink'),
            value: MENU_DICT.TYPE_INNERLINK,
          },
          {
            label: $t('menu.type.outLink'),
            value: MENU_DICT.TYPE_OUTLINK,
          },
        ],
      },
    },
    {
      field: 'perms',
      title: $t('menu.perms'),
    },
    {
      field: 'component',
      title: $t('menu.component'),
    },
    {
      field: 'isVisible',
      title: $t('menu.isVisible'),
      width: 100,
      cellRender: {
        name: 'CellTag',
        options: [
          {
            type: 'info',
            label: $t('common.yes'),
            value: true,
          },
          {
            type: 'primary',
            label: $t('common.no'),
            value: false,
          },
        ],
      },
    },
    {
      cellRender: { name: 'CellTag' },
      field: 'status',
      title: $t('common.status'),
    },
    {
      cellRender: {
        attrs: {
          nameField: 'menuName',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          {
            code: 'append',
            label: $t('page.action.add_children'),
            text: true,
            show: () => {
              return hasAccessByCodes(['sys_menu:add']);
            },
          },
          {
            code: 'edit',
            show: () => {
              return hasAccessByCodes(['sys_menu:edit']);
            },
          },
          {
            code: 'delete',
            text: true,
            disabled: (row: SysMenu) => {
              return !!(row.children && row.children.length > 0);
            },
            show: () => {
              return hasAccessByCodes(['sys_menu:remove']);
            },
          },
        ],
      },
      field: 'operation',
      fixed: 'right',
      align: 'center',
      headerAlign: 'center',
      showOverflow: false,
      title: $t('page.action.action'),
    },
  ];
}
